import { addCollectUsingPost, checkCollectStateUsingPost } from "@/services/music-recommend/collectController";
import { addCommentUsingPost, listCommentPageBySongIdUsingGet } from "@/services/music-recommend/commentController";
import { getSongByIdUsingGet, getSongFileUsingGet } from "@/services/music-recommend/songController";
import { FolderAddOutlined, PlayCircleOutlined, PlusOutlined } from "@ant-design/icons";
import { useModel, useSearchParams } from "@umijs/max";
import { Button, Col, Divider, Image, message, Row ,List} from "antd";
import { Comment } from '@ant-design/compatible';
import { Fragment, useEffect, useState } from "react";
import Editor from "./components/Editor";
import {  getCover, MP3_DEFAULT_IMG } from "@/utils/mp3LoadCover";





const SongDetailPage: React.FC = () => {

  const { initialState, setInitialState } = useModel('@@initialState');
  const [params] = useSearchParams();

  const [songInfo,setSongInfo] = useState<API.SongVO>({});
  const [cover,setCover] = useState('');
  const [collected,setCollected]= useState(false);
  const [comments, setComments] = useState<API.CommentVO[]>([]);

  const songId = params.get('id') ?? '';
  const userId = initialState?.currentUser?.id ?? -1;

  const getSongInfo = async ()=>{
    try {
      const respond = await getSongByIdUsingGet({id:Number(songId)});
      
      if(respond.code==0 && respond.data) {
        setSongInfo(respond.data);
      }
      
    } catch (error) {
      message.error('获取歌曲数据异常');
    }
  }

  const getCollectState= async (userId:number,songId:number)=>{
      
    const respond = await checkCollectStateUsingPost({userId:userId,songId:songId});
    setCollected(respond.data ?? false );
  };


  const getComments = async (songId:number)=>{
    const respond = await listCommentPageBySongIdUsingGet({
      songId: songId,
      pageSize: 40,
    });
    const comments = respond.data?.records;
    setComments(comments ?? []);
  };

  const loadSongCover = async (url:string) =>{
    // await getSongFileUsingGet({url:url});
    const img = await getCover(url);
    setCover(img);
  };

  useEffect(()=>{
    getSongInfo();
    getCollectState(userId,Number(songId));
    getComments(Number(songId));
    
  },[songId])

  useEffect(()=>{
    loadSongCover(songInfo.url ?? '');
  },[songInfo.url]);

//-----------

  const {id,name,singerName,tags,url} = songInfo;

  const [submitting,setSubmitting] = useState(false);
  const [editorValue, setEditorValue] = useState<string>('');

  

  // 播放歌曲
  const {
    first,
    setPlaying,
    songs,AddSong,
    setCurrentSong,setCurrentSongIndex,
  } = useModel("musicPlayerModel");

  const handleAdd = async (clickedRow:API.SongVO) =>{
    if(!clickedRow) return;

    AddSong(clickedRow);
    if(first) {
      setPlaying(true);
    }
  };

  const handlePlay = async (clickedRow:API.SongVO) =>{
    if(!clickedRow) return;
    //check is in songs list
    const index = songs.findIndex(item => item.id==clickedRow.id)
    if(index != -1) {
      setCurrentSong(clickedRow);
      setCurrentSongIndex(index);
    } else {
      const nextIndex = songs.length;
      AddSong(clickedRow);
      setCurrentSong(clickedRow);
      setCurrentSongIndex(nextIndex);
    }
    setPlaying(true);

  };

  const handleCollect = async (song:API.SongVO)=>{
    //handle collect or un-collect

    const songId = song.id;
    
    if(collected) {
      message.error("歌曲已收藏");
    }else {
  
      await addCollectUsingPost({userId:userId,songId:songId});
      setCollected(true);
      message.success("收藏成功");
    }

  };

  // 评论

  const handleTime = (time: string) => {
    const publishTime = new Date(time);
    const currentTime = new Date(Date.now());
    let result = publishTime.toLocaleDateString();
    if (result === currentTime.toLocaleDateString()) {
        result = `${publishTime.getHours()}:${publishTime.getMinutes()}`
    }
    return result
  };



  const handleEditorChange = (value: string)=>{
    setEditorValue(value);
  }

  const handleSubmit = async () => {
    try {
      setEditorValue(editorValue.trim());
      if(editorValue) {
        const respond = await addCommentUsingPost({
          content: editorValue,
          songId: Number(songId),
          userId: userId,
        })
        
        const newComment :API.CommentVO={
          content: editorValue,
          createTime: new Date(Date.now()).toLocaleDateString(),
          id: respond.data,
          userAvatar:initialState?.currentUser?.avatar,
          userName: initialState?.currentUser?.name,
        };
        setEditorValue('');
        setComments([...comments,newComment]);
        message.success('发送成功');
      }
    } catch (error) {
      message.error("评论失败");
    }
  }


  return (
    <Col>
      {/* img + name-singer + play-pause + love  */}
      <Row>
        <Image
          src={cover}
          height={130}
          width={130}
          preview={false}
        />

        <Col style={{marginLeft:50}}>
          <strong style={{fontSize:20}}>{name}</strong>
          <Col style={{marginTop:15,marginBottom:15}}>
            <span
              style={{color:'gray'}}
            >{'歌手: '+singerName}</span>
          </Col>
          <Row>
            <Button.Group>
              <Button  
                type="primary" 
                icon={<PlayCircleOutlined />} 
                style={{paddingLeft:7,paddingRight:7}}
                title="播放"
                onClick={()=>{handlePlay(songInfo);}}
              >
                播放
              </Button>
              <Button  
                type="primary" 
                icon={<PlusOutlined />} 
                style={{paddingLeft:5,paddingRight:5}}
                title="添加到播放列表"
                onClick={()=>{handleAdd(songInfo);}}
              ></Button>
            </Button.Group>
            
            <Button 
              icon={<FolderAddOutlined />} 
              style={{paddingLeft:7,paddingRight:7,marginLeft:12}}
              onClick={()=>{handleCollect(songInfo);}}
            >
              收藏
            </Button>
          </Row>
        </Col>
      </Row>

      <List
        className="comment-list"
        header={
          <div>
            <strong style={{fontSize: 22}}>评论</strong>
            <span style={{ marginLeft: 25 ,color:'gray'}}>
              {`共 ${comments.length ?? 0} 条评论`}
            </span>

            <Comment
              avatar={initialState?.currentUser?.avatar}
              content={
                <Editor
                  onChange={handleEditorChange}
                  onSubmit={handleSubmit}
                  submitting={submitting}
                  value={editorValue}
                />
              }
            />
          </div>
           
        }
        itemLayout="horizontal"
        dataSource={comments}
        rowKey={'id'}
        renderItem={item => (
          <li>
            <Comment
              // actions={item.actions}
              author={item.userName}
              avatar={item.userAvatar}
              content={item.content}
              datetime={handleTime(item.createTime ?? '')}
            />
          </li>
        )}
      />
    </Col>
  );


};

 export default SongDetailPage;